package com.traffic.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.annotation.Power;
import com.traffic.constant.Const;
import com.traffic.constant.Status;
import com.traffic.entity.AppConfig;
import com.traffic.exception.BaseException;
import com.traffic.mapper.AppConfigMapper;
import com.traffic.service.AppConfigService;
import com.traffic.util.JwtUtil;
import com.traffic.util.PowerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/24
 */
@Service
public class AppConfigServiceImpl extends ServiceImpl<AppConfigMapper, AppConfig> implements AppConfigService {
    @Autowired
    private AppConfigMapper appConfigMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PowerUtil powerUtil;

    /**
     * 返回当前启动的appConfig
     * @return
     */
    @Override
    public AppConfig getConfig() {
        QueryWrapper<AppConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("state", Const.CONFIG_START);
        AppConfig config = appConfigMapper.selectOne(wrapper);
        return config;
    }


    @Transactional
    @Override
    @Power(authority = Const.AUTH_TEXT)
    public AppConfig addOrEditConfig(AppConfig appConfig) {
        QueryWrapper<AppConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("state", Const.CONFIG_START);
        AppConfig old = appConfigMapper.selectOne(wrapper);

        if (ObjectUtil.isNotNull(old)) {
            old.setState(Const.CONFIG_CLOSE);
            appConfigMapper.updateById(old);
        }

        appConfig.setState(Const.CONFIG_START);
        appConfigMapper.insert(appConfig);
        return appConfig;
    }
}
